package com.ruoyi.web.controller.application;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ApplicationInfo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.model.ExaminationQuestions;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.http.HttpBakUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.shiro.util.AuthorizationUtils;
import com.ruoyi.system.mapper.ExaminationQuestionsMapper;
import com.ruoyi.system.service.IApplicationInfoService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报告信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/application/info")
public class ApplicationInfoController extends BaseController {

    private String prefix = "application/info";

    public static String FilesInFolderPath = "/Users/tony/Desktop/two";

    private final static String url = "https://video-test.youliancloud.cn/quark/information/createTablePng";

    @Autowired
    private IApplicationInfoService applicationInfoService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ExaminationQuestionsMapper examinationQuestionsMapper;

    @RequiresPermissions("application:info:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("application:info:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ApplicationInfo user) {
        startPage();
        List<ApplicationInfo> list = applicationInfoService.selectApplicationInfoList(user);
        return getDataTable(list);
    }

    @Log(title = "报告管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("application:info:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ApplicationInfo user) {
        List<ApplicationInfo> list = applicationInfoService.selectApplicationInfoList(user);
        ExcelUtil<ApplicationInfo> util = new ExcelUtil<ApplicationInfo>(ApplicationInfo.class);
        return util.exportExcel(list, "报告数据");
    }

    @Log(title = "报告管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("application:info:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ApplicationInfo> util = new ExcelUtil<ApplicationInfo>(ApplicationInfo.class);
        List<ApplicationInfo> userList = util.importExcel(file.getInputStream());
        String message = applicationInfoService.importApplicationInfo(userList, updateSupport, getLoginName());
        return AjaxResult.success(message);
    }

    @RequiresPermissions("application:info:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<ApplicationInfo> util = new ExcelUtil<ApplicationInfo>(ApplicationInfo.class);
        return util.importTemplateExcel("报告数据");
    }

    /**
     * 新增报告
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        return prefix + "/add";
    }

    /**
     * 新增保存报告
     */
    @RequiresPermissions("application:info:add")
    @Log(title = "报告管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated ApplicationInfo user) {
        if (!applicationInfoService.checkEmailUnique(user)) {
            return error("新增报告'" + user.getName() + "'失败，登录账号已存在");
        }
        user.setCreateBy(getLoginName());
        return toAjax(applicationInfoService.insertApplicationInfo(user));
    }

    /**
     * 修改保存报告
     */
    @RequiresPermissions("application:info:edit")
    @Log(title = "报告管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated ApplicationInfo user) {
        user.setUpdateBy(getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(applicationInfoService.updateApplicationInfo(user));
    }


    @RequiresPermissions("application:info:remove")
    @Log(title = "报告管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(Long[] ids) {
        return toAjax(applicationInfoService.deleteApplicationInfoByIds(ids));
    }


    /**
     * 新增报告
     */
    @GetMapping("/test")
    public String test(ModelMap mmap) {
        List<ExaminationQuestions> examinationQuestionsList = FileUtils.readFilesInFolder();
        int total = examinationQuestionsMapper.batchUpsert(examinationQuestionsList);
        return String.valueOf(total);
    }


    /**
     * 新增报告
     */
    @GetMapping("/spider")
    public String spider(ModelMap mmap) {
        for (int pageNum = 1; pageNum <= 1000; pageNum++) {
            Map mapParam = new HashMap();
            mapParam.put("pageNum", pageNum);
            mapParam.put("qAttriId", "26502");
            mapParam.put("qUserId", "486323");
            mapParam.put("orgId", "2504");
            mapParam.put("groupId", "965");
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(JSON.toJSONString(mapParam));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                String resultBody = HttpBakUtils.sendSpider(url, jsonObject, "utf-8");

                // 新文件名
                String fileName = pageNum + ".txt";

                // 文件内容
                String content = resultBody;

                Path filePath = Paths.get(FilesInFolderPath, fileName);

                try {
                    // 创建文件夹路径
                    Files.createDirectories(filePath.getParent());
                    // 创建文件，写入内容
                    Files.write(filePath, content.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            pageNum++;
        }


        List<ExaminationQuestions> examinationQuestionsList = FileUtils.readFilesInFolder();
        int total = examinationQuestionsMapper.batchUpsert(examinationQuestionsList);
        return String.valueOf(total);
    }

}